package repository

import (
	"fmt"
	"gorm.io/gorm/clause"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var BaseRepository = newBaseRepository()

func newBaseRepository() *baseRepository {
	return &baseRepository{}
}

type baseRepository struct {
}

func (b baseRepository) PageJoin(selectString string, joinString string, page int, pageSize int, keyword model.KeyWord,
	order clause.OrderByColumn) (pageResult model.PageResult, err error) {
	var res *interface{}
	var where string
	if keyword.KeywordColumn != "" {
		where = fmt.Sprintf("%s = ?", keyword.KeywordColumn)
		if err := db.DB.Select(selectString).Joins(joinString).Where(where, keyword.KeywordColumn).Order(order).Offset((page - 1) * pageSize).Limit(pageSize).Find(&res).Error; err != nil {
			return pageResult, err
		}
	} else {
		if err := db.DB.Select(selectString).Joins(joinString).Order(order).Offset((page - 1) * pageSize).Limit(pageSize).Find(&res).Error; err != nil {
			return pageResult, err
		}
	}
	total := totalRecords(selectString, joinString)
	totalPages := total / int64(pageSize)
	if total%int64(pageSize) != 0 {
		totalPages++
	}

	pageResult.PageSize = pageSize
	pageResult.Page = page
	pageResult.Total = totalPages
	pageResult.List = &res
	return pageResult, nil
}

// 获取总记录数
func totalRecords(selectString string, joinString string) (total int64) {
	db.DB.Select(selectString).Joins(joinString).Count(&total)
	return total
}
